<template>
  <div>
    <!-- 定义面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 定义卡片 -->
    <el-card class="box-card">

      <!-- 定义第一行数据 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryItemInfo.query" clearable @clear="getItemList">
            <el-button slot="append" icon="el-icon-search" @click="getItemList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addItemdialogVisible = true">添加商品</el-button>
        </el-col>
      </el-row>

      <!-- 获取商品列表数据 -->
      <el-table :data="itemList" style="width: 100%" stripe border>
        <el-table-column prop="id" label="序号" width="80px" >
        </el-table-column>
        <el-table-column prop="itemNum" label="商品号" width="80px">
        </el-table-column>
        <el-table-column prop="itemType" label="商品类型" width="100px">
        </el-table-column>
        <!-- ***************** -->
        <el-table-column prop="images" label="商品图片" width="200px">
          <template slot-scope="scope">
            <el-button type="primary"  size="mini" @click="imagesShow(scope.row.images)">图片预览</el-button>
          </template>
        </el-table-column>
        <!-- 使用过滤器修改时间 在main.js中定义过滤器 -->
        <el-table-column prop="price" label="价格(元)" width="80px">
          <template slot-scope="scope">
            {{scope.row.price | priceFormat}}
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态" width="80px">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status" active-color="#ff4949" inactive-color="#13ce66"
              @change="updateStatus(scope.row)"></el-switch>
          </template>
        </el-table-column>

        <el-table-column prop="updated" label="更新时间" width="100px" :formatter="formatDate">
        </el-table-column>
        <!-- <el-table-column prop="updated" label="更新时间" width="180px" :formatter="formatDate">
        </el-table-column> -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="updateItemBtn(scope.row)">修改</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteItemBtn(scope.row)">删除</el-button>
            <el-button type="success" icon="el-icon-edit" size="mini" @click="addBillBtn(scope.row)">添加信息</el-button>


          </template>
        </el-table-column>
      </el-table>


      <!-- 定义分页插件-->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryItemInfo.pageNum" :page-sizes="[1, 5, 10, 20]" :page-size="queryItemInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>

    </el-card>
    <!-- *************** -->
    <el-dialog title="商品新增" :visible.sync="addItemdialogVisible" width="50%" @close="closeAddItemDialog">
      <el-form :model="addItemForm" :rules="rules" ref="addItemForm" label-width="100px">
        <el-form-item label="1" prop="floor">
          <el-input v-model="addItemForm.floor"></el-input>
        </el-form-item>
        <el-form-item label="商品号" prop="itemNum">
          <el-input v-model="addItemForm.itemNum"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input v-model="addItemForm.price" type="number"></el-input>
        </el-form-item>
        <el-form-item label="商品类型" prop="itemType">
          <!-- 通过级联获取商品分类信息-->
          <el-input v-model="addItemForm.itemType"></el-input>
        </el-form-item>

        <el-form-item label="商品图片" prop="images">
          <el-upload class="upload-demo" :action="uploadUrl" :on-preview="handlePreview" :on-remove="handleRemove"
            :on-success="handleSuccess" list-type="picture" multiple drag>
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>

      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addItemdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoom">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加修改商品信息对话框 -->
    <el-dialog title="修改商品信息" :visible.sync="updateItemDialogVisible" width="50%">
      <!-- 定义分类表单 -->
      <el-form :model="updateItemForm" :rules="rules" ref="updateItemForm" label-width="100px">
        <el-form-item label="商品号:">
          <el-input v-model="updateItemForm.itemNum" disabled></el-input>
        </el-form-item>
        <el-form-item label="商品类型:" prop="itemType">
          <el-input v-model="updateItemForm.itemType"></el-input>
        </el-form-item>
        <el-form-item label="商品价格:">
          <el-input v-model="updateItemForm.price"></el-input>
		  {{updateItemForm.price | priceFormat}}
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateItemDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateItem">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="添加用户信息" :visible.sync="addBillDialogVisible" width="50%"
      @close="quxiao">
      <!-- 定义分类表单 -->
      <el-form :model="addBillForm" :rules="rules" ref="addBillForm" label-width="100px">
        <el-form-item label="真实姓名:" prop="userRealname">
          <el-input v-model="addBillForm.userRealname"></el-input>
        </el-form-item>
        <el-form-item label="电话:" prop="userPhone">
          <el-input v-model="addBillForm.userPhone"></el-input>
        </el-form-item>
        <el-form-item label="身份证号:" prop="userIdNum">
          <el-input v-model="addBillForm.userIdNum"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addBillDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addBill">确 定</el-button>
      </span>
    </el-dialog>

    <!-- *************** -->
    <el-dialog title="图片预览" :visible.sync="dialogImageVisible">
      <img :src="imageUrlPath" width="100%" height="100%" />
    </el-dialog>



  </div>
</template>

<script>
  export default {
    data() {
      //校验手机号规则
      const checkPhone = (rule, value, callback) => {

        //定义校验手机号的正则语法
        const phoneRege = /^1[3456789][0-9]{9}$/
        if (phoneRege.test(value)) {

          return callback()
        }
        callback(new Error('请填写正确的手机号'))

      }
      return {
        // *****************
        fits: ['fill'],
        addItemForm: {
          floor: '',
          itemNum: '',
          itemType: '',
          price: '',
          status: true,
          images: []
        },
        addItemdialogVisible: false,
        uploadUrl: "http://localhost:8099/file/upload",
		 // uploadUrl: "http://manage.ydc.com/file/upload"
        //uploadUrl: "http://172.233.5.149:8099/file/upload",
        imageUrlPath: "",
        //定义图片控制开关
        dialogImageVisible: false,
        addBillDialogVisible: false,


        addBillForm:{
          userRealname: '',
          userPhone: '',
          userIdNum: '',
          roomId: ''
        },
        //1.定义商品列表信息
        itemList: [],
        //2.定义分页对象
        queryItemInfo: {
          query: '', //定义查询参数
          pageNum: 1,
          pageSize: 10
        },
        updateItemForm: {
          itemType: '',
          itemNum: '',
          price: ''
        },
        rules: {
          floor: [{
            required: true,
            message: '请输入序号',
            trigger: 'blur'
          }],
          price: [{
            required: true,
            message: '请输入商品号',
            trigger: 'blur'
          }],
          itemNum: [{
            required: true,
            message: '请输入商品数量信息',
            trigger: 'blur'
          }],
          itemType: [{
            required: true,
            message: '请输入商品类型',
            trigger: 'blur'
          }],
          userPhone: [
            { required: true, message: '请输入电话', trigger: 'blur' },
            { min: 11, max: 11, message: '长度必须11个字符', trigger: 'blur' },
            { validator: checkPhone, trigger: 'blur' }
                    ],
          userRealname: [
            { required: true, message: '请输入姓名', trigger: 'blur' },
            { min: 2, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' }
          ],
          userIdNum: [
            { required: true, message: '请输入身份证号', trigger: 'blur' },
            { min: 18, max: 18, message: '输入正确的身份证号', trigger: 'blur' }
          ]
        },

        total: 0,
        updateItemDialogVisible: false
      }
    },
    created() {
      //1.获取商品列表数据
      this.getItemList()
    },
    methods: {
      quxiao(){
        this.addBillDialogVisible=false,
        this.$refs.addBillForm.resetFields()

      },
      //实现商品信息分页查询
      async getItemList() {
        const {
          data: result
        } = await this.$http.get("/item/getItemList", {
          params: this.queryItemInfo
        })
        if (result.status !== 200) return this.$message.error("商品列表查询失败")
        this.itemList = result.data.rows
        this.total = result.data.total
      },
      //通过JS格式化时间
      formatDate(row, column, cellValue, index) {
        let date = new Date(cellValue)
        let year = date.getFullYear()
        let month = (date.getMonth() + 1 + '').padStart(2, '0')
        let day = (date.getDate() + '').padStart(2, '0')
        let HH = (date.getHours() + '').padStart(2, '0')
        let MM = (date.getMinutes() + '').padStart(2, '0')
        let SS = (date.getSeconds() + '').padStart(2, '0')
        return year + '-' + month + '-' + day + ' ' + HH + ":" + MM + ":" + SS
      },
      //条数变化时 调用
      handleSizeChange(size) {
        this.queryItemInfo.pageSize = size
        this.getItemList()
      },
      //页码值变化时 调用
      handleCurrentChange(current) {
        this.queryItemInfo.pageNum = current
        this.getItemList()
      },

      // **************
      imagesShow(images){
        this.dialogImageVisible=true
        this.imageUrlPath = images
      },

      handlePreview(file) {
        //获取图片的虚拟路径
        this.imageUrlPath = file.response.data.urlPath
        this.dialogImageVisible = true
      },
      //移除图片的方法
      async handleRemove(file) {
        //移除数组中的数据
        let virtualPath = file.response.data.virtualPath
        //通过findIndex函数 获取数组中指定数据的位置
        let index = this.addItemForm.images.findIndex(x => x === virtualPath)
        //删除数组中指定的数据
        this.addItemForm.images.splice(index, 1)
        //删除服务中的文件
        let {
          data: result
        } = await this.$http.delete("/file/deleteFile", {
          params: {
            virtualPath: virtualPath
          }
        })
        if (result.status !== 200) return this.$message.error("删除图片失败")
        this.$message.success("删除图片成功")
      },
      //如果文件上传成功之后调用
      handleSuccess(response, file) {
        if (response.status !== 200) return this.$message.error("文件上传失败")
        file.name = response.data.fileName
        //获取虚拟路径
        let virtualPath = "http://image.ydc.com" + response.data.virtualPath
        //将数据封装到Form表单中
        this.addItemForm.images.push(virtualPath)
      },
      addRoom() {
        //对表单进行校验
        this.$refs.addItemForm.validate(async (valid) => {
          //判断是否通过
          // if (!valid) return this.$message.error("校验有BUG!")
          const {
            data: result
          } = await this.$http.post('/item/addItem', this.addItemForm)
          if (result.status !== 200){
            this.addItemForm.images = this.addItemForm.images.join(",")
            return this.$message.error('添加商品失败!')
            this.handleRemove()
          }
          this.addItemdialogVisible = false
          this.$message.success('添加商品成功!')
          this.getItemList()
        })
      },
      closeAddItemDialog() {
        //API
        this.$refs.addItemForm.resetFields()
      },





      async updateStatus(item) {
        const {
          data: result
        } = await this.$http.put("/item/updateItemStatus", item)
        if (result.status !== 200) return this.$message.error("更新状态失败")
        this.$message.success("更新状态成功")
        this.getItemList()
      },

      async deleteItemBtn(item) {

        //消息确认框
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          //根据id删除数据
          const {
            data: result
          } = await this.$http.delete('/item/deleteItemById/'+item.id)
          if (result.status !== 200) return this.$message.error("商品删除失败")
          this.$message.success("商品删除成功")
          //重新获取房间列表信息
          this.getItemList()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },

      updateItemBtn(item) {
        this.updateItemDialogVisible = true
        this.updateItemForm = item
      },
      async updateItem() {
        const {
          data: result
        } = await this.$http.post("/item/updateItem", this.updateItemForm)

        if (result.status !== 200) return this.$message.error("商品修改失败")
        this.$message.success("商品修改成功")
        this.updateItemDialogVisible = false
      },

      addBillBtn(room) {

        this.addBillDialogVisible = true
        this.addBillForm.roomId = room.id
      },

      addBill(){
        //对整个表单重新进行校验  1.获取表单的对象  2.进行数据校验
        this.$refs.addBillForm.validate(async valid => {
          if(!valid) return this.$message.error("请正确填写数据")
          //之后发起ajax请求实现用户新增
         const {
           data: result
         } = await this.$http.post("/bill/addBill", this.addBillForm)

         if (result.status !== 200) return this.$message.error("添加失败")
         this.$message.success("添加成功")
         this.addBillDialogVisible = false
         this.getItemList()
        })
      }

    }
  }
</script>
<!-- 防止组件样式冲突 -->
<style lang="less" scoped>

</style>
